/**
 * http.js  请求ajax
 * author:cometang  time:2022-07-16
 */
const baseUrl = 'http://47.96.154.185:3701'

//传入对象---返回 &aaa=111&bb=222
function formatData(data) {
    let str = '';
    for (let key in data) {
        str += `&${key}=${data[key]}`
    }
    str = str.slice(1);
    return str;
}


let http = {
    //封装get 
    get: function (url, callback) {
        //添加token 
        let token = ''
        if (localStorage.getItem('token')) {
            token = localStorage.getItem('token')
        }

        let xhr = new XMLHttpRequest();
        xhr.open('get', baseUrl + url);
        //设置 token 请求头
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);

        xhr.send()
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status === 200) {
                callback(JSON.parse(xhr.responseText))
            }
        }

    },
    post: function (url, data, callback) {

        //添加token 
        let token = ''
        if (localStorage.getItem('token')) {
            token = localStorage.getItem('token')
        }


        let xhr = new XMLHttpRequest();
        //请求方式 请求地址
        xhr.open('post', baseUrl + url)
        //请求头设置- 模仿form表单提交数据  提交json数据 
        xhr.setRequestHeader('content-type', 'application/json');
        //设置 token 请求头
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        //发送 +数据  key=val&key1=val1
        xhr.send(JSON.stringify(data))
        xhr.onreadystatechange = function () {
            //判断 步骤到了最后一步 4
            if (xhr.readyState == 4 && xhr.status === 200) {
                // console.log(xhr.responseText);  //json字符串
                callback(JSON.parse(xhr.responseText))
            }
        }

    },
    //发送文件
    uploadFile: function (url, key, value, callback) {
        //添加token 
        let token = ''
        if (localStorage.getItem('token')) {
            token = localStorage.getItem('token')
        }

        //1.创建一个ajax 
        let xhr = new XMLHttpRequest();
        //2.创建一个 form表单 并 写入数据
        let fd = new FormData();
        fd.append(key, value);
        //请求方式 请求地址
        xhr.open('post', baseUrl + url)
        //设置 token 请求头
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        //发送 +数据  
        xhr.send(fd);

        xhr.onreadystatechange = function () {
            //判断 步骤到了最后一步 4
            if (xhr.readyState == 4 && xhr.status === 200) {
                // console.log(xhr.responseText);  //json字符串
                callback(JSON.parse(xhr.responseText))
            }
        }

    }


}

//将http对象 挂在到 window上
window.http = http;
window.baseUrl = baseUrl;